/*
 * QuickBuyDialog.java
 * business
 *
 * Created by ChenTao on 2017/2/25.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.widget.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yidiandao.business.R;
import com.yidiandao.business.data.bean.Goods;
import com.yidiandao.business.data.bean.Shop;
import com.yidiandao.business.data.model.IShoppingCartHelperModel;
import com.yidiandao.business.data.model.ShoppingCartHelperModel;
import com.yidiandao.business.ui.main.shoppingcart.confirmorder.ConfirmOrderActivity;
import com.yidiandao.business.utils.KeyboardUtils;
import com.yidiandao.business.utils.UIUtils;

/**
 * 快速够买Dialog
 */
public class QuickBuyDialog extends Dialog implements TextWatcher, View.OnClickListener {

    private static final String TAG = QuickBuyDialog.class.getSimpleName();

    private Context mContext;

    private TextView mTvTitle;

    private ImageView mTvSubtract;

    private EditText mEtCount;

    private ImageView mTvAdd;

    private TextView mTvTotalPrice;

    private Button mBtnPutIntoShoppingCart;

    private Button mBtnBuyNow;

    private RelativeLayout mRlytClose;

    private Goods mGoods;

    private int mGoodsCount;

    private int mMinGoodsCount = 1;

    private int mMaxGoodsCount;

    private IShoppingCartHelperModel mHelperModel;

    public QuickBuyDialog(Context context) {
        super(context, R.style.ThemeNoTitleDialog);
        mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mHelperModel = new ShoppingCartHelperModel();
        setContentView(R.layout.dialog_quick_buy);
        initViews();
    }

    private void initViews() {
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvSubtract = (ImageView) findViewById(R.id.tv_subtract);
        mEtCount = (EditText) findViewById(R.id.et_count);
        mTvAdd = (ImageView) findViewById(R.id.tv_add);
        mTvTotalPrice = (TextView) findViewById(R.id.tv_total_price);
        mBtnPutIntoShoppingCart = (Button) findViewById(R.id.btn_shopping_cart);
        mBtnBuyNow = (Button) findViewById(R.id.btn_buy_now);
        mRlytClose = (RelativeLayout) findViewById(R.id.rlyt_close);

        mTvAdd.setOnClickListener(this);
        mTvSubtract.setOnClickListener(this);
        mRlytClose.setOnClickListener(this);
        mBtnBuyNow.setOnClickListener(this);
        mBtnPutIntoShoppingCart.setOnClickListener(this);
    }

    /**
     * 初始化商品
     */
    public void setGoods(Goods goods) {
        mGoods = goods;

        // 没有优惠活动，则显示立即立即购买，否则不显示立即购买
        if (TextUtils.isEmpty(goods.getFavourableNotice())) {
            mBtnBuyNow.setVisibility(View.VISIBLE);
            mBtnPutIntoShoppingCart.setBackgroundResource(R.drawable.sl_dialog_right);
        } else {
            // 只显示加入购物车
            mBtnBuyNow.setVisibility(View.GONE);
            mBtnPutIntoShoppingCart.setBackgroundResource(R.drawable.sl_dialog_bottom);
        }

        // 设置数量不超过库存
        int stockNumber = goods.getStockNumber();
        mMinGoodsCount = goods.getMinNumber() < 1 ? 1 : goods.getMinNumber();

        // 商品数量为 最少起订量
        mGoodsCount = mMinGoodsCount;

        if (mGoodsCount == 1) {
            setSubtractButtonEnable(false);
        }

        // 限制购买量
        // -1 表示无限制
        mMaxGoodsCount = (goods.getLimitNumber() == -1) ? stockNumber : goods.getLimitNumber();
        mEtCount.setText(mGoodsCount + "");
        mTvTitle.setText(goods.getGoodsName());

        mEtCount.addTextChangedListener(this);

        setGoodsPrice();
    }

    /**
     * 设置商品价格
     */
    private void setGoodsPrice() {
        float totalPrice = getGoodsCount() * mGoods.getGoodsPrice();
        mTvTotalPrice.setText(UIUtils.getString(R.string.dialog_total_price, totalPrice));
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    private String getEditTextContent() {
        return mEtCount.getText().toString().trim();
    }

    public void setSubtractButtonEnable(boolean enable) {
        mTvSubtract.setEnabled(enable);
    }

    @Override
    public void afterTextChanged(Editable s) {

        String inputText = s.toString();

        if (!TextUtils.isEmpty(inputText)) {
            int inputNumber = Integer.parseInt(inputText);
            if (inputNumber != 0) {
                // 输入的不是0
                mGoodsCount = inputNumber;
                // 设置减号可用/不可用
                setSubtractButtonEnable(mGoodsCount > 1);
            } else {
                // 输入内容为0时，设置为1
                setGoodsCount(1);
            }
        } else {
            // 输入的内容为空
            mGoodsCount = 1;
        }

        if (mGoodsCount > mMaxGoodsCount) {
            // 超过最大值时，需要将显示设置为最大值
            setGoodsCount(mMaxGoodsCount);
            UIUtils.showToast(UIUtils.getString(R.string.goods_stock_not_enough_now, mMaxGoodsCount));
        }

        setGoodsPrice();
    }

    private int getGoodsCount() {
        return mGoodsCount;
    }

    private void setGoodsCount(int goodsCount) {
        if (goodsCount > mMaxGoodsCount) {
            UIUtils.showToast(UIUtils.getString(R.string.goods_stock_not_enough_now, mMaxGoodsCount));
            mGoodsCount = mMaxGoodsCount;
            return;
        }

        if (goodsCount < 1) {
            // 设置最少数量为1
            mGoodsCount = 1;
            setSubtractButtonEnable(false);
        } else {
            setSubtractButtonEnable(true);
        }

        mGoodsCount = goodsCount;
        // 商品数量
        mGoods.setGoodsNumber(goodsCount);
        mEtCount.setText(mGoodsCount + "");
        mEtCount.setSelection(getEditTextContent().length());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_subtract:
                // 减少
                mGoodsCount--;
                setGoodsCount(mGoodsCount);
                break;
            case R.id.tv_add:
                // 增加
                mGoodsCount++;
                setGoodsCount(mGoodsCount);
                break;
            case R.id.rlyt_close:
                dismiss();
                break;
            //立即购买
            case R.id.btn_buy_now:
                buyNow();
                break;
            // 加入购物车
            case R.id.btn_shopping_cart:
                addToShoppingCart();
                break;
        }
    }

    private void buyNow() {
        if (mGoodsCount < mMinGoodsCount) {
            UIUtils.showToast(UIUtils.getString(R.string.min_number, mMinGoodsCount));
            setGoodsCount(mMinGoodsCount);
            return;
        }

        mHelperModel.buyNow(TAG, mGoods.getGoodsId(), mGoodsCount, new IShoppingCartHelperModel.OnBuyNowListener() {
            @Override
            public void onSuccess() {
                // 跳转到确认订单页面
                toConfirmOrderActivity();
                dismiss();
            }
        });
    }

    private void addToShoppingCart() {

        // 修改为最小起订量
        if (mGoodsCount < mMinGoodsCount) {
            UIUtils.showToast(UIUtils.getString(R.string.min_number, mMinGoodsCount));
            setGoodsCount(mMinGoodsCount);
            return;
        }

        mHelperModel.addToCart(TAG, mGoods.getGoodsId(), mGoodsCount, new IShoppingCartHelperModel.OnAddToShoppingCartListener() {

            @Override
            public void onSuccess(Shop shop, Goods goods) {
                UIUtils.showToast(UIUtils.getString(R.string.goodsdetail_tip2));
                dismiss();
            }
        });
    }

    private void toConfirmOrderActivity() {
        ConfirmOrderActivity.actionStart((Activity) mContext, false);
    }

    @Override
    public void dismiss() {
        super.dismiss();

        if (mContext instanceof Activity) {
            KeyboardUtils.closeKeyboard((Activity) mContext);
        }
    }
}
